package com.car.rental.auth.filter;

import com.car.rental.auth.utils.RedisUtil;
import com.car.rental.common.utils.JwtUtils;

import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.lang.NonNull;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtils jwtUtils;
    private final RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("Authorization");
        System.out.println("Received token: " + token);  // 打印接收到的token

        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            System.out.println("Processed token: " + token);  // 打印处理后的token
        }

        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        try {
            // 验证token
            if (!jwtUtils.validateToken(token)) {
                throw new RuntimeException("token非法");
            }

            // 检查token是否在黑名单中
            if (redisUtil.isInBlacklist(token)) {
                throw new RuntimeException("token已失效");
            }

            // 获取用户名
            String username = jwtUtils.getUsernameFromToken(token);

            // 存入SecurityContextHolder
            UsernamePasswordAuthenticationToken authenticationToken = 
                new UsernamePasswordAuthenticationToken(username, null, Collections.emptyList());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } catch (Exception e) {
            // 打印异常信息，方便调试
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        // 放行
        filterChain.doFilter(request, response);
    }
} 